import os

from database.elasticsearch.es import ES
from database.mapper import stock_day_info, stock_info, boards_info
from utils import date_util, excel_util, parse_util, dict_util

module = "stock-info"
es = ES()
es.module = "stock-info"

all_stock_day_info = {}


def get_stock_day_sum(codes: list, beg_rq: str):
    result_list = []  # {'rq':rq,'sum':sum, 'timestamp':timestamp}
    result_dict = {}
    for code in codes:
        day_info = dict_util.get_default(all_stock_day_info, code, '')
        if day_info == '':
            day_info = stock_day_info.select_from_asc(code, beg_rq)
            all_stock_day_info[code] = day_info
        for di in day_info:
            rq = di.get('rq')
            main_io = int(di.get('main_io') / 10000)
            result_dict[rq] = main_io + dict_util.get_default(result_dict, rq, 0)
    for key in result_dict.keys():
        result_list.append({'rq': key, 'sum': result_dict.get(key), 'sort': date_util.get_date_int(key)})
    result_list = sorted(result_list, key=lambda x: x['sort'])
    return result_list


def del_module():
    es.delete_match_all({'module': module})
    # es.delete_match({'traceId': module})


def init_params():
    print(es.search_term({'code': '600031'}))
    print(es.search_sort({'code': '600031'}, es.get_sort_body([], "rq", "desc")))
    print(es.search_sort({'code': 'BK0145'}, es.get_sort_body([], "rq", "desc")))


def init_all_info():
    es.title = 'stockSumAllA'
    es.traceId = 'stockSumAllA000000'
    beg_rq = '2021-07-01'
    count = 0
    total = 0
    search_sort = es.search_sort({'code': 'ssa'}, es.get_sort_body([], "rq", "desc"))
    if search_sort is not None and len(search_sort) > 0:
        beg_rq = date_util.add_day_str(search_sort[0]['rq'], 1)
        total = search_sort[0]['total']
        count = search_sort[0]['count']
    sum_ios = stock_day_info.select_sum_io_rq('f_main_io', beg_rq)
    data_list = []
    for sum_io in sum_ios:
        count += 1
        body = {}
        body['rq'] = sum_io.get('rq')
        body['sum'] = round(sum_io.get('sum') / 100000000, 2)
        body['total'] = total = total + round(sum_io.get('sum') / 100000000, 2)
        body['name'] = 'aStock'
        body['code'] = 'ssa'
        body['count'] = count
        es.index(body)
        data_list.append({'日期': sum_io.get('rq'),
                          '当天和': round(sum_io.get('sum') / 100000000, 2),
                          '累计和': total})
    excel_util.gen_an_excel_this_path(os, data_list, "A")


def init_stock_info():
    # stock_all = stock_monitor.select_distinct()
    stock_all = stock_info.selectall()
    for si in stock_all:
        try:
            code = si.get('code')
            name = si.get('name')
            es.title = 'stockSumOne'
            traceId = 'stockSumOne' + code
            es.traceId = traceId
            count = 0
            total = 0
            beg_rq = '2021-07-01'
            search_sort = es.search_sort({'code': code}, es.get_sort_body([], "rq", "desc"))
            if search_sort is not None and len(search_sort) > 0:
                beg_rq = date_util.add_day_str(search_sort[0]['rq'], 1)
                total = search_sort[0]['total']
                count = search_sort[0]['count']
            result_list = get_stock_day_sum([code], beg_rq)
            for sum_io in result_list:
                count += 1
                body = {}
                body['rq'] = sum_io.get('rq')
                main_io = sum_io.get('sum')
                body['main_io'] = main_io
                body['total'] = total = total + main_io
                body['name'] = name
                body['code'] = code
                body['count'] = count
                body['sort'] = sum_io.get('sort')
                es.index(body)
            # ios = stock_day_info.select_from_asc(code, beg_rq)
            # for sum_io in ios:
            #     count += 1
            #     body = {}
            #     body['rq'] = sum_io.get('rq')
            #     main_io = int(sum_io.get('main_io') / 10000)
            #     body['main_io'] = main_io
            #     body['total'] = total = total + main_io
            #     body['name'] = name
            #     body['code'] = code
            #     body['count'] = count
            #     es.index(body)
        except Exception as e:
            print('error' + str(si))


def init_board_info():
    # stock_all = stock_monitor.select_distinct()
    # stock_all = stock_info.selectall()
    board_code_all = boards_info.select_all_board_code()
    for board_code in board_code_all:
        try:
            es.title = 'boardSum'
            traceId = 'boardSum' + board_code
            es.traceId = traceId
            count = 0
            total = 0
            beg_rq = '2021-07-01'
            search_sort = es.search_sort({'code': board_code}, es.get_sort_body([], "rq", "desc"))
            if search_sort is not None and len(search_sort) > 0:
                beg_rq = date_util.add_day_str(search_sort[0]['rq'], 1)
                total = search_sort[0]['total']
                count = search_sort[0]['count']
            board_all = boards_info.select_board_detail(board_code)
            board_name = board_all[0].get('board_one')
            result_list = get_stock_day_sum(parse_util.list_dict_to_list(board_all, 'code'), beg_rq)
            for sum_io in result_list:
                count += 1
                body = {}
                body['rq'] = sum_io.get('rq')
                body['sum'] = sum_io.get('sum')
                body['total'] = total = total + sum_io.get('sum')
                body['name'] = board_name
                body['code'] = board_code
                body['count'] = count
                es.index(body)

            # sum_ios = stock_day_info.select_sum_io_rq_codes('f_main_io', beg_rq,
            #                                                 parse_util.list_dict_to_list(board_all, 'code'))
            # data_list = []
            # for sum_io in sum_ios:
            #     count += 1
            #     body = {}
            #     body['rq'] = sum_io.get('rq')
            #     body['sum'] = int(sum_io.get('sum') / 10000)
            #     body['total'] = total = total + int(sum_io.get('sum') / 10000)
            #     body['name'] = board_name
            #     body['code'] = board_code
            #     body['count'] = count
            #     es.index(body)
            #     data_list.append({'日期': sum_io.get('rq'),
            #                       '当天和': int(sum_io.get('sum') / 100000000, 2),
            #                       '累计和': total})
            # excel_util.gen_an_excel_this_path(os, data_list, board_name)
        except Exception as e:
            print('error' + str(board_code))


if __name__ == '__main__':
    print('abcd')
    init_params()
    # get_stock_day_sum(['600031'], '2021-07-01')
    del_module()
    # init_all_info()
    # init_board_info()
    # init_stock_info()
